package com.itcrx.datastructure.circular;

/**
 * @author NoobMaster69  * @date 2024/6/16 0016 星期日 15:28
 */

import java.util.Iterator;

/**
 * 环形链表
 */
public class DoublyLinkedListSentinel implements Iterable<Integer>{
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = sentinel.next;
            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    private static class Node{
        Node prev;
        int value;
        Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    private Node sentinel = new Node(null,-1,null);

    /**
     * 哨兵即为头也是尾巴 贪吃蛇
     */
    public DoublyLinkedListSentinel() {
        sentinel.next = sentinel;
        sentinel.prev = sentinel;
    }

    /**
     * 节点添加到第一个
     * @param value
     */
    public void addFirst(int value) {
        Node a = sentinel;
        Node b = sentinel.next;
        Node addNode = new Node(a,value,b);
        a.next = addNode;
        b.prev = addNode;
    }

    /**
     * 添加节点到最后一个
     * @param value 值
     */
    public void addLast(int value) {
        Node a = sentinel.prev;
        Node b = sentinel;
        Node addNode = new Node(a,value,b);
        a.next = addNode;
        b.prev = addNode;
    }
    private static IllegalArgumentException IllegalIndex(int index) {
        return new IllegalArgumentException(String.format("index [%d] 不存在%n", index));
    }

    /**
     * 删除第一个
     */
    public void removeFirst() {
        Node removed = sentinel.next;
        if(removed == sentinel){
            throw new IllegalArgumentException("非法");
        }
        Node a = sentinel;
        Node b = removed.next;
        a.next = b;
        b.prev = a;
    }

    /**
     * 删除最后一个
     */
    public void removeLast(){
        Node removed = sentinel.prev;
        if(removed == sentinel){
            throw new IllegalArgumentException("非法");
        }
        Node a = removed.prev;
        Node b = sentinel;
        a.next = b;
        b.prev = a;
    }

    /**
     * 根据值删除
     * @param index 索引值
     */
    public void removeByValue(int value) {
        Node removed = findByValue(value);
        if(removed == null){
            throw IllegalIndex(value);
        }
        Node a = removed.prev;
        Node b = removed.next;
        a.next = b;
        b.prev = a;
    }

    private Node findByValue(int value){
        for (Node p = sentinel.next; p != sentinel; p = p.next) {
            if(p.value == value){
                return p;
            }
        }
        return null;
    }

}
